/*******************************************************************************
* CSCI321 Major Project 2010 - University of Wollongong                        *
********************************************************************************
* Program:		WeaveEdit                                              *
* Authors:		Simon Allen (Student#: 3457527, Unix: sa655)           *
*			Scott Bellis (Student#: 3479110, Unix: sjb900)         *
*			Jason Benger (Student#: 3454137, Unix: jb960)          *
*			Timothy Newmarch (Student#: 3459263 Unix: tgn336)      *
*			Benjamin Richardson (Student# 3467752, Unix: bjr401)   *
* Supervisor:		Daniel F. Saffioti                                     *
* Modified:		28/10/2010                                             *
* Description:		WeaveEdit is a highly portable collaborative text      *
*			editor and word processor, allowing several users to   *
*			read and edit multiple documents at the same time.     *
*			It is available for Mac OS X, Windows and Linux,       *
*			utilising Nokia's Qt development framework.            *
*******************************************************************************/


#include "cstyleindenter.h"
#include "Editor/texteditor.h"


/**
  * Indent a line using custom automatic indentation rules defined below.
  */
void CStyleIndenter::indent()
{
	QTextCursor cursor = editor->textCursor();
	QChar ch = editor->document()->characterAt(cursor.position() - 2);
	int numTabs = 0, newLinePos = cursor.position() - 2;
	bool newLevel = false;
	bool closeBlock = false;

	// We have a new level of indentation.
	if (ch == Qt::Key_BraceLeft)
	{
		numTabs = 1;
		newLevel = true;
	}

	// We are on the same level of indentation as the current block.
	else
	{
		while (newLinePos >= 0 && !(editor->document()->characterAt(newLinePos).unicode() == Qt::Key_BraceLeft
					    || editor->document()->characterAt(newLinePos).unicode() == Qt::Key_BraceRight))
			newLinePos--;

		if (editor->document()->characterAt(newLinePos).unicode() == Qt::Key_BraceRight)
			closeBlock = true;
	}

	// No current block found, so invalid indentation, just set default.
	if (newLinePos >= 0)
		numTabs = 1;

	// Go back from the opening brace until we hit a new line/start of doc and count tabs.
	while (newLinePos >= 0 && editor->document()->characterAt(newLinePos).toAscii() != '\0')
	{
		if (editor->document()->characterAt(newLinePos) == '\t')
			numTabs++;

		newLinePos--;
	}

	if (numTabs > 0)
	{
		if (closeBlock)
			numTabs--;

		if (newLevel)
		{
			editor->insertPlainText(QString(numTabs, '\t') + '\n' + QString(numTabs - 1, '\t'));

			for (int i = 0; i < numTabs; i++)
				cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
		}

		else
			editor->insertPlainText(QString(numTabs, '\t'));
	}

	editor->setTextCursor(cursor);
}
